package cn.com.headfree.point.service.impl;

import cn.com.headfree.depterprela.service.IDeptErpRelaService;
import cn.com.headfree.depterprela.service.OrgDeptService;
import cn.com.headfree.entity.*;
import cn.com.headfree.entity.isc.User;
import cn.com.headfree.point.dao.PersonYearPointDao;
import cn.com.headfree.point.dao.PersonYearPointDetailDao;
import cn.com.headfree.point.dao.PointRuleDao;
import cn.com.headfree.point.dao.RuleElementDao;
import cn.com.headfree.point.service.ISalaryUserDataInfoService;
import cn.com.headfree.point.service.PersonYearPointDetailService;
import cn.com.headfree.point.service.PointRuleService;
import cn.com.headfree.recordlog.service.IRecordLogService;
import cn.com.headfree.salary.dao.SalaryDao;
import cn.com.headfree.salary.service.IUserDataInfoService;
import cn.com.headfree.vo.TPersonYearPointDetailVo;
import cn.com.headfree.vo.YearEffectVo;
import com.gta.edu.sdk.common.dto.Page;
import com.gta.edu.sdk.util.IdGen;
import com.gta.edu.sdk.util.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service("personYearPointDetailService")
@Transactional
public class PersonYearPointDetailServiceImpl implements PersonYearPointDetailService {

	private static final Logger log = LogManager.getLogger(PersonYearPointDetailServiceImpl.class);

	@Autowired
	private PersonYearPointDetailDao personYearPointDetailDao;

	@Autowired
	private PersonYearPointDao personYearPointDao;

	@Autowired
	private IDeptErpRelaService deptErpRelaService;

	@Autowired
	private SalaryDao salaryDao;

	@Autowired
	private IRecordLogService recordLogService;

	@Autowired
	private OrgDeptService orgDeptService;

	@Autowired
	private IUserDataInfoService userDataInfoService;

	@Autowired
	private ISalaryUserDataInfoService salaryUserDataInfoService;

	@Override
	public void findPersonYearPointDetailPageList(Page<TPersonYearPointDetailVo> page, TPersonYearPointDetailVo personYearPointDetail) {
		personYearPointDetailDao.findPersonYearPointDetailPageList(page,personYearPointDetail);
	}

	@Override
	public List<TPersonYearPointDetail> findPersonYearPointDetailList(TPersonYearPointDetailVo personYearPointDetail) {
		return personYearPointDetailDao.findPersonYearPointDetailList(personYearPointDetail);
	}

	@Override
	public void saveInfo(TPersonYearPointDetail personYearPointDetail, User user) {
		//如果已经有积分明细，则覆盖
		personYearPointDetailDao.deletePersonYearPointDetailInfo(personYearPointDetail.getSalaryId());
		//如果是对审核不通过的申报进行编辑再提交，则将申报数据由不通过修改为待审核
		salaryDao.updateSalaryState(personYearPointDetail.getSalaryId(),"0",null);
		personYearPointDetail.setErpNo(user.getFax());
		personYearPointDetail.setUserName(user.getName());
		personYearPointDetail.setCreaterId(user.getFax());
		personYearPointDetail.setCreaterName(user.getName());
		personYearPointDetail.setCreateTime(new Date());
		personYearPointDetail.setUpdaterId(user.getFax());
		personYearPointDetail.setUpdaterName(user.getName());
		personYearPointDetail.setUpdateTime(new Date());
		personYearPointDetail.setOrgId(user.getBaseOrgId());
		personYearPointDetail.setDelSign(0);
		//所属部门（一级部门）
		TOrgDept dept = new TOrgDept();
		dept = getDeptId(user.getDeptId(),dept,user);
		personYearPointDetail.setDeptId(dept.getId());
		personYearPointDetail.setDeptName(dept.getName());
		//获取上年度剩余积分
		if(personYearPointDetail.getYear() != null){
			List<TPersonYearPoint> lastYearPoints = personYearPointDao.getLastYearPointByErpNo(user.getFax(),personYearPointDetail.getYear() - 1);
			if(lastYearPoints != null && lastYearPoints.size() > 0){
				personYearPointDetail.setLastYearPoint(lastYearPoints.get(0).getRemainPoint());
				personYearPointDetail.setSalaryGrade(lastYearPoints.get(0).getSalaryGrade());
			}
		}
		if(personYearPointDetail.getLastYearPoint() != null && personYearPointDetail.getYearPoint() != null){
			personYearPointDetail.setTotalPoint(personYearPointDetail.getYearPoint() + personYearPointDetail.getLastYearPoint());
		}else if(personYearPointDetail.getLastYearPoint() != null && personYearPointDetail.getYearPoint() == null){
			personYearPointDetail.setTotalPoint(personYearPointDetail.getLastYearPoint());
		}else if(personYearPointDetail.getLastYearPoint() == null && personYearPointDetail.getYearPoint() != null){
			personYearPointDetail.setTotalPoint(personYearPointDetail.getYearPoint());
		}
		if(personYearPointDetail.getTotalPoint() != null){
			//不满4分合计不变
			personYearPointDetail.setTrimTotalPoint(personYearPointDetail.getTotalPoint());
			personYearPointDetail.setTrimSalaryGrade(personYearPointDetail.getSalaryGrade());
			if(personYearPointDetail.getTotalPoint()>=4){
				//满4分可以调整
				salaryGradeRule(personYearPointDetail);
			}
		}
		personYearPointDetailDao.saveInfo(personYearPointDetail);

		//TODO 涉及资料添加salaryId 关联
		salaryUserDataInfoService.salaryUserDataInfoByPointDetail(personYearPointDetail);
		//日志
		TRecordOptLog log = new TRecordOptLog();
		log.setCurrentRecordId(personYearPointDetail.getSalaryId());
		log.setRecordId(personYearPointDetail.getSalaryId());
		log.setOptType("0");
		log.setOptContent(user.getName()+"提报了薪档调整申请");
		recordLogService.save(user,log);
	}

	@Override
	public List<TPersonYearPointDetail> getTPersonYearPointDetailInfo(String salaryId) {
		return personYearPointDetailDao.getTPersonYearPointDetailInfo(salaryId);
	}

	@Override
	public void auditRejectInfo(String salaryId, User user,String auditOpt) {
		//先修改薪档申报状态--由待审核变更为不同意
		salaryDao.updateSalaryState(salaryId,"2",auditOpt);
		//删除积分明细
		personYearPointDetailDao.deletePersonYearPointDetailInfo(salaryId);
		//日志
		TRecordOptLog log = new TRecordOptLog();
		log.setOptType("8");
		if(StringUtil.isNullOrEmpty(auditOpt)){
			log.setOptContent(user.getName()+"驳回了该薪档申请");
		}else{
			log.setOptContent(user.getName()+"驳回了该薪档申请，驳回理由是："+auditOpt);
		}
		log.setCurrentRecordId(salaryId);
		log.setRecordId(salaryId);
		recordLogService.save(user,log);
	}

	//获取当前登录人所在一级部门ID
	public TOrgDept getDeptId(String deptId,TOrgDept orgDept,User user){
		TOrgDept dept = orgDeptService.getOrgDeptById(deptId);
		if(dept != null){
			if(dept.getpId().equals(user.getBaseOrgId())){
				orgDept.setId(dept.getId());
				orgDept.setName(dept.getName());
			}else{
				getDeptId(dept.getpId(),dept,user);
			}
		}
		return dept;
	}

	@Override
	public TPersonYearPointDetailVo getPersonalYearPointDetail(String year,
			String orgId,String erpNo) {
		return personYearPointDetailDao.getPersonalYearPointDetail(year,orgId,erpNo);
	}


	/**
	 * 岗级升级规则
	 * 绿色区域为基本区域(1-6)，当年积分满4分即可晋升
	 * 虚线区域为成长区域(7-11)，需要满足当年积分为4分，绩效为A或者有专家人才称号积分，方可晋升
	 * 当达到员工所在岗级上限即12时，必须通过岗位晋升才可提升岗级
	 * @param personYearPointDetail
	 */
	public void salaryGradeRule(TPersonYearPointDetail personYearPointDetail){
		String salaryGrade = personYearPointDetail.getSalaryGrade();
		if(StringUtils.isNotBlank(salaryGrade)){
			String[] salaryGradeArr = salaryGrade.split("_");
			String first = salaryGradeArr[0];
			String tail = salaryGradeArr[1];
			int intTail = Integer.valueOf(tail);
			String restail = String.format("%02d",intTail+1);
			String trimSalaryGrade = String.format("%s_%s",first,restail);
			if(intTail<6){
				personYearPointDetail.setTrimTotalPoint(personYearPointDetail.getTotalPoint()-4);
				personYearPointDetail.setTrimSalaryGrade(trimSalaryGrade);
			}else if(intTail>=6&&intTail<12){
				List<YearEffectVo> yearEffectVos = userDataInfoService.getYearEffectByErpNo(personYearPointDetail.getErpNo(),personYearPointDetail.getYear());
				if(yearEffectVos != null && yearEffectVos.size() > 0){
					YearEffectVo yearEffectVo = yearEffectVos.get(0);
					if("A".equals(yearEffectVo.getPerforGrade())||personYearPointDetail.getExpertPoint()>0){
						personYearPointDetail.setTrimTotalPoint(personYearPointDetail.getTotalPoint()-4);
						personYearPointDetail.setTrimSalaryGrade(trimSalaryGrade);
					}
				}
			}
		}
	}


	/**
	 *  01_01-26_12
	 * 执行岗级升级规规则 --- 舍弃不用
	 * @param salaryGrade
	 * @author sunwenchang
	 *
	 */
	public String salaryGradeUpgradeRule(String salaryGrade){
		String trimSalaryGrade = salaryGrade;
		if(StringUtils.isNotEmpty(salaryGrade)&&salaryGrade.length()==5){
			String[] salaryGradeArr = salaryGrade.split("_");
			String first = salaryGradeArr[0];
			String tail = salaryGradeArr[1];
			int intFirst = Integer.valueOf(first);
			int intTail = Integer.valueOf(tail);
			if (intTail<12&&intTail>0){
				intTail++;
				String restail = String.format("%02d",intTail);
				trimSalaryGrade = String.format("%s_%s",first,restail);
			}else{
				if (intFirst==26){
					return salaryGrade;
				}
				intFirst++;
				String resFirst = String.format("%02d",intFirst);
				trimSalaryGrade = String.format("%s_%s",resFirst,"01");
			}
		}
		return trimSalaryGrade;
	}


	public void saveFromSalaryInfo(TPersonYearPointDetail personYearPointDetail, User createUser) {
		personYearPointDetail.setCreaterId(createUser.getFax());
		personYearPointDetail.setCreaterName(createUser.getName());
		personYearPointDetail.setCreateTime(new Date());
		personYearPointDetail.setUpdaterId(createUser.getFax());
		personYearPointDetail.setUpdaterName(createUser.getName());
		personYearPointDetail.setUpdateTime(new Date());
		personYearPointDetail.setDelSign(0);
		//获取上年度剩余积分
		if(personYearPointDetail.getYear() != null){
			List<TPersonYearPoint> lastYearPoints = personYearPointDao.getLastYearPointByErpNo(personYearPointDetail.getErpNo(),personYearPointDetail.getYear() - 1);
			if(lastYearPoints != null && lastYearPoints.size() > 0){
				personYearPointDetail.setLastYearPoint(lastYearPoints.get(0).getRemainPoint());
				personYearPointDetail.setSalaryGrade(lastYearPoints.get(0).getSalaryGrade());
			}
		}
		if(personYearPointDetail.getLastYearPoint() != null && personYearPointDetail.getYearPoint() != null){
			personYearPointDetail.setTotalPoint(personYearPointDetail.getYearPoint() + personYearPointDetail.getLastYearPoint());
		}else if(personYearPointDetail.getLastYearPoint() != null && personYearPointDetail.getYearPoint() == null){
			personYearPointDetail.setTotalPoint(personYearPointDetail.getLastYearPoint());
		}else if(personYearPointDetail.getLastYearPoint() == null && personYearPointDetail.getYearPoint() != null){
			personYearPointDetail.setTotalPoint(personYearPointDetail.getYearPoint());
		}
		if(personYearPointDetail.getTotalPoint() != null){
			//不满4分合计不变
			personYearPointDetail.setTrimTotalPoint(personYearPointDetail.getTotalPoint());
			personYearPointDetail.setTrimSalaryGrade(personYearPointDetail.getSalaryGrade());
			if(personYearPointDetail.getTotalPoint()>=4){
				//满4分可以调整
				salaryGradeRule(personYearPointDetail);
			}
		}
		personYearPointDetailDao.saveInfo(personYearPointDetail);

		//TODO 涉及资料添加salaryId 关联
		salaryUserDataInfoService.salaryUserDataInfoByPointDetail(personYearPointDetail);
		//日志
		TRecordOptLog log = new TRecordOptLog();
		log.setCurrentRecordId(personYearPointDetail.getSalaryId());
		log.setRecordId(personYearPointDetail.getSalaryId());
		log.setOptType("0");
		log.setOptContent(createUser.getName()+"提报了薪档调整申请");
		recordLogService.save(createUser,log);
	}
}
